package com.hornsun.Quartz;

/**
 * Created by 编译中... on 2018/6/28.
 */

import com.hornsun.config.ConfigInfo;
import com.hornsun.config.IRedisService;
import com.hornsun.data.dbo.AccountInfo;
import com.hornsun.data.dbo.Authorization;
import com.hornsun.data.dbo.ClientInfo;
import com.hornsun.data.dbo.OfflineInfo;
import com.hornsun.data.repository.AuthorizationRepository;
import com.hornsun.util.SerializeUtils;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Set;


@DisallowConcurrentExecution
public class OfflineFormJob implements Job {

    @Autowired
    private AuthorizationRepository authorizationRepository;

    @Autowired
    private IRedisService service;

    @Autowired
    private ConfigInfo configInfo;

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        Set<String> accounts = service.getKeys(configInfo.getRedisAccount());
        Date now = new Date();
        for (String account : accounts) {
            byte[] clientInfoBytes = (byte[]) service.get(configInfo.getRedisAccount(),account);
            ClientInfo clientInfo = (ClientInfo) SerializeUtils.deSerialize(clientInfoBytes);
            List<OfflineInfo> offlineInfoList = clientInfo.getOfflineInfoList();
            List<AccountInfo> accountInfoList = clientInfo.getAccountInfoList();
            Authorization authorization = clientInfo.getAuthorization();
            if (authorization==null){
                if(!authorizationRepository.whetherAuthByName(account)){
                    service.remove(configInfo.getRedisAccount(),account);
                    continue;
                }else {
                    clientInfo.setAuthorization(authorizationRepository.getByName(account));
                }
            }
            for (int i=0;i<offlineInfoList.size();i++){
                //账号达到最大离线时间，删除、标识有空位
                if (now.getTime()-offlineInfoList.get(i).getTime().getTime()>=authorization.getOfflineTime()*60*1000){
                    offlineInfoList.remove(offlineInfoList.get(i));
                    if (accountInfoList.size()==0&&offlineInfoList.size()==0){
                        service.remove(configInfo.getRedisAccount(),account);
                    }else {
                        service.put(configInfo.getRedisAccount(),account, SerializeUtils.serialize(clientInfo),-1);
                    }
                }
            }
        }


    }
}
